package com.mmall.util;

import com.mmall.common.RedisPool;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;

/**
 * @author Paul
 * @version 0.1
 * @date 2018/8/15 0015
 */
@Slf4j
public class RedisPoolUtil {
    public static String set(String key, String value) {
        try (Jedis jedis = RedisPool.getJedis()) {
            return jedis.set(key, value);
        } catch (Exception e) {
            log.error("set key:{} value:{} error", key, value, e);
            return null;
        }
    }

    public static String get(String key) {
        try (Jedis jedis = RedisPool.getJedis()) {
            return jedis.get(key);
        } catch (Exception e) {
            log.error("set key:{} error", key, e);
            return null;
        }
    }

    /**
     * 设置有效期
     *
     * @param key
     * @param value
     * @param exTime 单位是秒
     * @return
     */
    public static String setEX(String key, String value, int exTime) {
        try (Jedis jedis = RedisPool.getJedis()) {
            return jedis.setex(key, exTime, value);
        } catch (Exception e) {
            log.error("set key:{} value:{} error", key, value, e);
            return null;
        }
    }

    /**
     * 根据key设置有效期
     * @param key
     * @param exTime
     * @return
     */
    public static Long setEX(String key, int exTime) {
        try (Jedis jedis = RedisPool.getJedis()) {
            return jedis.expire(key, exTime);
        } catch (Exception e) {
            log.error("set key:{} value:{} error", key, e);
            return 0L;
        }
    }

    /**
     * 删除一个键值
     * @param key
     * @return
     */
    public static Long del(String key) {
        try (Jedis jedis = RedisPool.getJedis()) {
            return jedis.del(key);
        } catch (Exception e) {
            log.error("set key:{} error", key, e);
            return null;
        }
    }
}
